package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 移动端用户管理
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送短信
     */
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String code = RandomStringUtils.random(4, false, true);
        //1. 调用短信工具类发送短信
        //SMSUtils.sendSms(user.getPhone(), code);
        //2. 将验证码保存到session中
        session.setAttribute("code", code);
        log.info("短信发送成功：{}", code);
        return R.success("短信发送成功");
    }

    /**
     * 短信登录
     */
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        //1. 验证码对比
        String code1 = map.get("code");
        String code2 = (String) session.getAttribute("code");
        if (!StringUtils.equals(code1, code2)) {
            return R.error("验证码错误");
        }
        //2. 判断手机号是否存在
        //先根据手机号查询 select * from user where phone=?
        String phone = map.get("phone");
        User user = userService.query()
                .eq("phone", phone)
                .one();
        if (user == null) {
            //说明用户新用户，添加一条数据
            user = new User();
            user.setPhone(phone); //手机号
            userService.save(user); //保存之前，user的id是没有数据的
        }
        //3. 将user的id存入session
        session.setAttribute("user", user.getId());
        //4. 响应数据，user
        return R.success(user);
    }
}
